package com.wxg.print;

import java.io.File;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import com.wxg.entity.MyPage;
import com.wxg.entity.MyPages;
import com.wxg.utils.MyFileReader;
import com.wxg.utils.MyFileWriter;

/**
 * date: 2018年2月9日<br>
 * @author Wxg
 *
 */
public class BuildFinalPrintPage {
	private Document doc;
	private MyFileWriter writer;
	private MyPages pages;
	
	public BuildFinalPrintPage(String genFilepath, MyPages pages){
		// this.genFilepath = genFilepath;
		this.pages = pages;
		this.writer = new MyFileWriter("html_");
		try {
			this.doc = Jsoup.parse(new File(genFilepath), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String finalPrintPage(){
		head();
		main();
		foot();
		return writer.getFilepath();
	}
	
	private void main(){
		MyFileReader mfr = null;
		int i = 1; // 页码
		for(MyPage page : pages.getPages()){
			// page_header : 要放到page循环中
			mfr = new MyFileReader("com/wxg/html/a102/pageHeader.html");
			for(String str : mfr.list()){
				writer.writeb(str);
			}
			
			for(String id : page.getIds()){
				writer.writeb( doc.getElementById(id).outerHtml() );
			}
			
			// page_footer : 要放到page循环中
			mfr = new MyFileReader("com/wxg/html/a102/pageFooter.html");
			for(String str : mfr.list()){
				if(str.contains("{{page}}")){
					str = str.replace("{{page}}", i+"");
				}
				writer.writeb(str);
			}
			i++;
		}
	}
	
	private void head(){
		writer.writeb("<html>");
		// head
		writer.writeb("<head>");
		// 提取原html中的head内容
		if(null != doc){
			Element head = doc.getElementsByTag("head").get(0);
			for(Element ele : head.children()){
				writer.writeb( ele.outerHtml() );
			}
		}
		//加入自己的style(放在后面)
		MyFileReader mfr = new MyFileReader("com/wxg/html/a102/mystyle.html");
		for(String str : mfr.list()){
			writer.writeb(str);
		}
		writer.writeb("</head>");
		// body
		writer.writeb("<body>");
	}
	
	private void foot(){
		writer.writeb("</body>");
		writer.writeb("</html>");
		writer.close();
	}
}
